package view.cms.desktop
{
    import flash.display.DisplayObject;
    import flash.events.*;
    import flash.geom.*;
    import flash.system.*;
    import flash.ui.Keyboard;
    import flash.utils.*;
    
    import model.ModelLocator;
    
    import mx.collections.*;
    import mx.containers.Canvas;
    import mx.controls.*;
    import mx.core.*;
    import mx.effects.*;
    import mx.events.FlexEvent;
    import mx.managers.*;
    import mx.utils.*;
    
    import view.cms.desktop.events.*;    
	
    public class DrawingPage extends Container implements IFocusManagerComponent 
    {
        public static const PAGE_WIDTH:Number = 600
        public static const PAGE_HEIGHT:Number = 400;

		public var delArr:Array = [];
        public var loaded:Boolean;
        public var numOutstandingChildren:Number;
        private var resizeDMpRp:Point;
		
        private var maxY:int = 0;
        
        [Embed(source="/../assets/images/bltrcursor.png")]
        private var bltrCursorSymbol:Class;
        [Embed(source="/../assets/images/lrcursor.png")]
        private var lrCursorSymbol:Class;
        [Embed(source="/../assets/images/tlbrcursor.png")]
        private var tlbrCursorSymbol:Class;        
        [Embed(source="/../assets/images/tbcursor.png")]
        private var tbCursorSymbol:Class;                
        [Embed(source="/../assets/images/handcursor.png")]
        private var handCursorSymbol:Class;        
        [Embed(source="/../assets/images/movecursor.png")]
        private var moveCursorSymbol:Class; 
        [Embed(source="/../assets/images/dragcursor.png")]
        private var dragCursorSymbol:Class;        

        private var selectedChildren:Array;
        public var newShape:DrawingShape;
        private var _manipulator:Manipulator;
        private var _canvasHeight:Number;
        private var moveDMpMp:Point; // mouse to manipulator vector
        private var activeCursorID:int;
        private var hasMoved:Boolean;
        private var resizeAngle:Number;
        private var moveStartPoint:Point;
        private var _moving:Boolean;
        private var _canvasWidth:Number;
        private var rotateCenter:Point;
        private var _groupManager:GroupManager;
        private var resizeStartPoint:Point;
        private var _backgroundSolidColor:uint;
        private var _tooltip:ToolTip;
        
        private var switchModeIfUnmoved:Boolean;
        private var _center:Point;
        
        public static const DRAG:String = "drag";
        public static const SELECT:String = "select";
		
		public var pid:int;
		
		public var m:ModelLocator;
		
		public var selected:DrawingShape;

        public function DrawingPage(width_:Number=600, height_:Number=400)
        {
//        	this.blendMode = BlendMode.LAYER;
			this.selected = null;
			this.m = ModelLocator.getInstance();
        	this.creationPolicy = "all";
            _moving = false;
            _canvasWidth = 0;
            _canvasHeight = 0;
            _backgroundSolidColor = 0xaaaaaa;
            numOutstandingChildren = 0;
            loaded = false;
            selectedChildren = new Array();
            this.width = width_;
            this.height = height_;
            this._center = new Point(width_/2,height_/2);
            this.clipContent = false;
//            this.setBounds();
            this.focusEnabled = true;
            this.mouseFocusEnabled = true;
            this._groupManager = new GroupManager();
            this.addEventListener(SelectEvent.SELECT_DESKTOP, this.completeDesktopSelection);
            this.addEventListener(SelectEvent.SELECT, this.completeSelection);
            this.addEventListener(SelectEvent.SWITCH_SELECT, this.completeSwitchSelection);
            this.addEventListener(CursorChangeEvent.CHANGE, this.setCursor);
            this.addEventListener("selectionChanged", this.refreshManipulator);
            this.addEventListener(FocusEvent.FOCUS_IN, this.focusChanged);
			this.addEventListener(FocusEvent.FOCUS_OUT, this.focusChanged);
            this.addEventListener(MouseEvent.MOUSE_DOWN, this.unselect);
            this.addEventListener(KeyboardEvent.KEY_DOWN, this.handleKey);
//            this.addEventListener(MouseEvent.ROLL_OVER, this.setTip);
            this.addEventListener(FlexEvent.CREATION_COMPLETE,init);
        } 

 		private function init(event:Event):void
		{
		}
		
		public function destroy():void
		{
            this.removeEventListener(FlexEvent.CREATION_COMPLETE,init);
		}
		
        override public function addChild(child:DisplayObject):DisplayObject
        {
            if ( (child is DrawingObject) && !(DrawingObject(child).loaded) )
            {
                numOutstandingChildren++;
                this.loaded = false;
                child.addEventListener("objectLoaded", this.childLoaded);
            };
            
            return super.addChild(child);
        }
        
        public function childLoaded(evt:Event):void
        {
            evt.target.removeEventListener("objectLoaded", this.childLoaded);
            numOutstandingChildren--;
            if ( numOutstandingChildren <= 0 )
            {
                this.loaded = true;
		        dispatchEvent(new Event("pageLoaded"));
            };
        }        
        
        public function handleKey(evt:KeyboardEvent):void
        {
            switch (evt.keyCode)
            {
                case Keyboard.DELETE:
                    if (manipulator != null)
                    {
                        this.deleteSelectedChildren();
                    };
				break;

                case Keyboard.F6:
                	trace("focus:"+this.getFocus().toString());
                	trace("real focus:"+this.focusManager.getFocus());
				break;
				
                default:
                    trace(("keycode: " + evt.keyCode));
                break;
            };
        }
        
        public function deleteSelectedChildren():void
        {
            removeListeners();
            
            var i:int = 0;
            
			var item:DrawingShape;
			
            while (i < selectedChildren.length) 
            {
//				
//				this.m.cmsSite.resultArr.push(xml);
				
//				if(DrawingShape(selectedChildren[i]).propertiesXML.prop.(@label=='action')[0].@value=="add")
//				{
//					DrawingShape(selectedChildren[i]).propertiesXML.prop.(@label=='action')[0].@value = "";
//				}
//				else
//					DrawingShape(selectedChildren[i]).propertiesXML.prop.(@label=='action')[0].@value = "del";
//				trace("删除条目" + (DrawingShape(selectedChildren[i]).propertiesXML.prop.(@label=='action')[0].@value));
//				//TODO 从后台删除数据
//				DrawingShape(selectedChildren[i]).visible = false;
//				DrawingShape(selectedChildren[i]).includeInLayout = false;
//				DrawingShape(selectedChildren[i]).deactivate();
//				removeListeners(selectedChildren[i]);
				
				
				item = DrawingShape(selectedChildren[i]);
				if(item.propertiesXML.prop.(@label=='action')[0].@value!='add')
				{
					
					var temp:int;
					
					var obj:Object = {};
					obj.pageId = int(item.propertiesXML.prop.(@label=='pageId')[0].@value);	
					obj.subId = int(item.propertiesXML.prop.(@label=='subId')[0].@value);	
					obj.subId2 = int(item.propertiesXML.prop.(@label=='subId2')[0].@value);	
					obj.pos = int(item.propertiesXML.prop.(@label=='pos')[0].@value);
					obj.pos2 = int(item.propertiesXML.prop.(@label=='pos2')[0].@value);
//					temp = int(item.propertiesXML.prop.(@label=='subId2')[0].@value)
//					if(temp!=0)
//					else 
//						obj.subId = int(item.propertiesXML.prop.(@label=='subId')[0].@value);
//					
//					temp = int(item.propertiesXML.prop.(@label=='pos2')[0].@value);
//					if(temp!=0)
//						obj.pos = int(item.propertiesXML.prop.(@label=='pos2')[0].@value);
//					else
//						obj.pos = int(item.propertiesXML.prop.(@label=='pos')[0].@value);
//					
					obj.action = "del";
					
					item.propertiesXML.prop.(@label=='action')[0].@value = "del";
					delArr.push(obj);   //保存到删除队列中
				}	
trace("删除本身action不为add的元素： 如果是add则直接删除  " + item.propertiesXML.prop.(@label=='action')[0].@value);				
				
                this.removeChild(selectedChildren[i]);
//                if ( selectedChildren[i] == this.desktopPhoto )
//                	this.desktopPhoto = null;
                
                selectedChildren[i] = null;
                
                i++;
            };
			//调用后台删除选中元素
//			if(arr.length>0)
//				m.cmsSite.delegate.delSitePages(arr);
			
            resetSelectedChildren();
        }

        public function unselect(b:Boolean=true):void
        {
            this.removeListeners();
           	resetSelectedChildren();         	
            	
//            if (b){
//                dispatchEvent(new Event("unselect", true));
//            };
        }
        
        private function removeListeners(obj:DrawingObject=null):void
        {
            if ( _manipulator && this.contains(_manipulator) )
            {
                this.removeChild(_manipulator);
                _manipulator = null;
	            dispatchEvent(new CursorChangeEvent(CursorChangeEvent.CHANGE, true, true, null));
            };
            
            if (obj == null)
            {
                var i:int = 0;
                
                while (i < selectedChildren.length) 
                {
                    this.removeEventListener(ShiftEvent.SHIFT, selectedChildren[i].shift);
                    this.removeEventListener(ResizeEvent.RESIZE_SHAPE, selectedChildren[i].resize);
                    selectedChildren[i].selected = false;
                    selectedChildren[i].invalidateDisplayList();
                    i++;
                };
            } 
            else 
            {
                this.removeEventListener(ShiftEvent.SHIFT, obj.shift);
                this.removeEventListener(ResizeEvent.RESIZE_SHAPE, obj.resize);
                obj.selected = false;
                obj.invalidateDisplayList();
            };
        }
		

		/**
		 * 添加单个元素 
		 * @param datum   元素对象
		 * @param isArea   是否是区域
		 * 
		 */		
        public function addItem(datum:Object=null,isArea:Boolean=false):void
        {
        	if ( datum )
        	{
				var layout:XML = new XML(datum.layout);
	            newShape = new DrawingShape(layout.@width,layout.@height,0xffffff,1,this.pid,isArea,datum);
                newShape.x = layout.@x;
                newShape.y = layout.@y;
                
                this.maxY = Math.max(int(layout.@y)+int(layout.@height)+20,this.maxY);
                this.height = this.maxY;
                trace(this.maxY);
        	}
        	else
        	{
	            newShape = new DrawingShape(60,60,0xffffff,1,this.pid,isArea,null);
        	}
    	
            removeListeners();
            resetSelectedChildren();
            this.addChild(newShape);
            newShape.activate();
			
			
			if ( isArea )
	            this.moveDepth(newShape,0);//移到最底层
            
            if ( !datum )
			{
	            newShape.x = 0;
	            //newShape.y = 0;
	            newShape.y = this.contentMouseY;
	            newShape.findExtents();
	            addToSelectedChildren(newShape);
	            makeManipulator();
	            this.addListeners();
	            this.setFocus();
	        	ModelLocator.getInstance().cmsSite.onElementSelected(newShape);
				

				newShape.propertiesXML.prop.(@label=='action')[0].@value = 'add';  //标识为新添加的元素
trace("增加条目-------------------" + newShape.propertiesXML.prop.(@label=='action')[0].@value);				

//				this.m.cmsSite.resultArr.push(xml);
	  		}
        }

        public function get allLocked():Boolean
        {
            var result:Boolean = true;
            var i:int = 0;
            
            while (i < selectedChildren.length) 
            {
                if (selectedChildren[i].locked == false)
                {
                    result = false;
                    break;
                };
                i++;
            };
            return result;
        }

        private function resetSelectedChildren():void
        {
            selectedChildren = [];
            dispatchEvent(new Event("selectionChanged", true));
        }

        private function addToSelectedChildren(obj:DrawingObject):void
        {
			var g:Array = _groupManager.findGroupFor(obj);
            
            if ( g )
            {
                var i:int = 0;
                
                while (i < g.length) 
                {
                    if (selectedChildren.indexOf(g[i]) == -1)
                    {
                        selectedChildren.push(g[i]);
                    };
                    i++;
                };
            } 
            else 
            {
                selectedChildren.push(obj);
            };
            
            dispatchEvent(new Event("selectionChanged", true));
        }
        
        public function hookCardData(data:*):void
        {
        	if ( this.selected )
        	{
        		this.selected.setValue('productId',data.id);
        		this.selected.setValue('linkURL',data.url);
        		this.selected.setValue('linkTitle',data.title);
        		this.selected.setValue('imageSrc',data.big);
        		this.selected.setValue('imageAlt',data.title);
        		this.selected.setValue('title',data.title);
        		this.selected.setValue('productType',2);
				
				updateSitePageAction();
        	}
        }

        public function hookBookData(data:*):void
        {
        	if ( this.selected )
        	{
        		this.selected.setValue('productId',data.id);
        		this.selected.setValue('linkURL',data.url);
        		this.selected.setValue('linkTitle',data.title);
        		this.selected.setValue('imageSrc',data.big);
        		this.selected.setValue('imageAlt',data.title);
        		this.selected.setValue('title',data.title);
        		this.selected.setValue('productType',1);
				
				updateSitePageAction();
        	}
        }

        public function hookAvatarData(data:*):void
        {
        	if ( this.selected )
        	{
        		this.selected.setValue('productId',data.id);
        		this.selected.setValue('linkURL',data.url);
        		this.selected.setValue('linkTitle',data.name);
        		this.selected.setValue('imageSrc',data.big);
        		this.selected.setValue('imageAlt',data.name);
        		this.selected.setValue('title',data.name);
        		this.selected.setValue('productType',4);
        	}
        }

        public function hookUserData(data:*):void
        {
        	if ( this.selected )
        	{
        		this.selected.setValue('productId',data.bid);
        		this.selected.setValue('linkURL',data.url);
        		this.selected.setValue('linkTitle',data.nickname);
        		this.selected.setValue('imageSrc',data.big);
        		this.selected.setValue('imageAlt',data.nickname);
        		this.selected.setValue('title',data.nickname);
        		this.selected.setValue('productType',3);
				
				updateSitePageAction();
        	}
        }
		
		public function updateSitePageAction():void
		{
			if(selected.propertiesXML.prop.(@label=='action')[0].@value!="add")
			{
				selected.propertiesXML.prop.(@label=='action')[0].@value = "update";
			}
		}

        private function completeSwitchSelection(evt:SelectEvent):void
        {			
        	this.m.cmsSite.onElementSelected(DrawingShape(evt.selectedObject));
        	
        	if ( this.m.lock )
        	{
				if ( !DrawingShape(evt.selectedObject).isArea )	
				{		
        			this.m.cmsSite.switchToProduct();
		            this.selected = DrawingShape(evt.selectedObject);
    			}
    			
        		return;
        	}
        }
        
        private function completeSelection(evt:SelectEvent):void
        {			
        	this.m.cmsSite.onElementSelected(DrawingShape(evt.selectedObject));
        	
        	if ( this.m.lock )
        		return;
//        	this.m.cmsSite.onElementSelected(DrawingShape(evt.selectedObject));
//        	
//        	if ( this.m.lock )
//        	{
//				if ( !DrawingShape(evt.selectedObject).isArea )	
//				{		
//        			this.m.cmsSite.switchToProduct();
//		            this.selected = DrawingShape(evt.selectedObject);
//    			}
//    			
//        		return;
//        	}
        	
            this.removeListeners();
            
            if (!evt.shiftKey)
            {
                resetSelectedChildren();
            };
            
            this.selected = DrawingShape(evt.selectedObject);
            
            if ( !DrawingShape(evt.selectedObject).isArea )
	            this.moveDepth(DisplayObject(evt.selectedObject));
            
            DrawingObject(evt.selectedObject).findExtents();
            addToSelectedChildren(DrawingObject(evt.selectedObject));
            this.makeManipulator();
            this.addListeners();

            if (evt.fromClick)
            {
                this.startMove(new Point(_manipulator.x, _manipulator.y),false);
            };
        }

        private function completeDesktopSelection(evt:SelectEvent):void
        {
            this.removeListeners();
            
            if (!evt.shiftKey)
            {
                resetSelectedChildren();
            };
			
            DrawingObject(evt.selectedObject).findExtents();
            addToSelectedChildren(DrawingObject(evt.selectedObject));
            this.makeManipulator();
            this.addListeners();
            
            if (evt.fromClick)
            {
                this.startMove(new Point(_manipulator.x, _manipulator.y),false);
            };
        }

        private function addListeners():void
        {
            var i:int = 0;
            
            while (i < selectedChildren.length) 
            {
                DrawingObject(selectedChildren[i]).setSelectionVars(_manipulator.angle);
                this.addEventListener(ShiftEvent.SHIFT, selectedChildren[i].shift);
                this.addEventListener(ResizeEvent.RESIZE_SHAPE, selectedChildren[i].resize);
                selectedChildren[i].selected = true;
                selectedChildren[i].invalidateDisplayList();
                i++;
            };
        }
        
        private function makeManipulator():void
        {
            if (selectedChildren.length == 0)
            {
                this.dispatchEvent(new Event("changeToolbar", true));
                return;
            };
            
            if (selectedChildren.length == 1)
            {
                _manipulator = new Manipulator(selectedChildren[0].TLC.x, selectedChildren[0].TLC.y, selectedChildren[0].width, selectedChildren[0].height, selectedChildren[0].angle, selectedChildren[0].resizable);
                
/* 				BindingUtils.bindProperty(_manipulator, "x", selectedChildren[0], "x");                 
				BindingUtils.bindProperty(_manipulator, "y", selectedChildren[0], "y");                 
				BindingUtils.bindProperty(_manipulator, "width", selectedChildren[0], "width");                 
				BindingUtils.bindProperty(_manipulator, "height", selectedChildren[0], "height");                  */
                
                if ( !(selectedChildren[0] is DrawingShape) )
                {
                    this.dispatchEvent(new Event("changeToolbar", true));
                };
                
            } 
            else 
            {
                var minx:Number = selectedChildren[0].x;
                var miny:Number = selectedChildren[0].y;
                var maxx:Number = 0;
                var maxy:Number = 0;
                var i:int = 0;
                
                while (i < selectedChildren.length) 
                {
                    selectedChildren[i].findExtents();
                    if (selectedChildren[i].minx < minx){
                        minx = selectedChildren[i].minx;
                    };
                    if (selectedChildren[i].miny < miny){
                        miny = selectedChildren[i].miny;
                    };
                    if (selectedChildren[i].maxx > maxx){
                        maxx = selectedChildren[i].maxx;
                    };
                    if (selectedChildren[i].maxy > maxy){
                        maxy = selectedChildren[i].maxy;
                    };
                    i++;
                };
                
                _manipulator = new Manipulator(minx,miny,maxx-minx,maxy - miny, 0, true);
                this.dispatchEvent(new Event("changeToolbar", true));
            };
            
            this.addChild(_manipulator);
        }

        private function setCursor(evt:CursorChangeEvent):void
        {
            if (evt.toCursor == null)
            {
                if (activeCursorID >= 0)
                {
                    CursorManager.removeCursor(activeCursorID);
                    activeCursorID = -1;
                } 
                else if (CursorManager.currentCursorID != CursorManager.NO_CURSOR)
                {
                    CursorManager.removeCursor(CursorManager.currentCursorID);
                    activeCursorID = -1;
                };
            } 
            else if (evt.toCursor == "drag")
            {
                activeCursorID = CursorManager.setCursor(dragCursorSymbol, 2, -12, -12);
            } 
            else if (evt.toCursor == "move")
            {
                activeCursorID = CursorManager.setCursor(moveCursorSymbol);
            } 
            else if (evt.toCursor == "hand")
            {
                activeCursorID = CursorManager.setCursor(handCursorSymbol);
            } 
            else if (evt.toCursor == "tlbr")
            {
                activeCursorID = CursorManager.setCursor(tlbrCursorSymbol, 1, -16, -16);
            } 
            else if (evt.toCursor == "bltr")
            {
                activeCursorID = CursorManager.setCursor(bltrCursorSymbol, 1, -16, -16);
            } 
            else if (evt.toCursor == "lr")
            {
                activeCursorID = CursorManager.setCursor(lrCursorSymbol, 1, -16, -11);
            } 
            else if (evt.toCursor == "tb")
            {
                activeCursorID = CursorManager.setCursor(tbCursorSymbol, 1, -10, -15);
            } 
            else if (evt.toCursor == "busy")
            {
				activeCursorID = Number(CursorManager.setBusyCursor());
            };
        }

        private function refreshManipulator(evt:Event):void
        {
            if (_manipulator)
            {
                _manipulator.invalidateDisplayList();
            };
        }
        
        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
        {
            graphics.clear();
            graphics.beginFill(_backgroundSolidColor, 1);
            graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
            graphics.endFill();
            super.updateDisplayList(unscaledWidth,unscaledHeight);
        }
    	
        private function focusChanged(evt:FocusEvent):void
        {
            this.invalidateDisplayList();
        }
    	
        public function setBounds():void
        {
            _canvasWidth = this.unscaledWidth;
			_canvasHeight = this.unscaledHeight;
            this.scrollRect = new Rectangle(0, 0, _canvasWidth, _canvasHeight);
            this.invalidateDisplayList();
        }

        public function getObjects():Array
        {
            var objs:Array;
            var i:int = 0;
            objs = this.getChildren();
            
            if ( _manipulator != null && (i=objs.indexOf(_manipulator)) != -1 )
            {
                objs.splice(i, 1);
            };
            
            return (objs);
        }

        private function removeFromSelectedChildren(obj:DrawingObject):void
        {
            var g:Array = _groupManager.findGroupFor(obj);
            if (g)
            {
                var i:int = 0;
                while (i < g.length) 
                {
                    if (selectedChildren.indexOf(g[i]) != -1)
                    {
                        removeListeners(g[i]);
                        selectedChildren.splice(selectedChildren.indexOf(g[i]), 1);
                    };
                    i++;
                };
            } 
            else if (selectedChildren.indexOf(obj) != -1)
            {
                removeListeners(obj);
                selectedChildren.splice(selectedChildren.indexOf(obj), 1);
            };

			dispatchEvent(new Event("selectionChanged", true));
        }
    	
        public function selectAndUnselect(evt:Boolean=true):void
        {
            if ( _manipulator && this.contains(_manipulator) )
            {
                this.removeChild(_manipulator);
                _manipulator = null;
            };
            
            var objs:Array = this.getObjects();
            var i:int = objs.length-1;
            
            while (i >= 0) 
            {
                if (DrawingObject(objs[i]).hitTestPoint(DrawingObject(objs[i]).stage.mouseX, DrawingObject(objs[i]).stage.mouseY, true))
                {
                    if ( !(objs[i].selected) && objs[i].selectable )
                    {
                        addToSelectedChildren(objs[i]);
                        break;
                    } 
                    else 
                    {
                        if (objs[i].selected)
                        {
                            removeFromSelectedChildren(objs[i]);
                            break;
                        };
                    };
                };
                
                i--;
            };
            
            this.makeManipulator();
            this.addListeners();
            
            if ( _manipulator && evt)
            {
                this.startMove(new Point(_manipulator.x, _manipulator.y),false);
            };
        }
        
        public function hitShapeUnderManip():Boolean
        {
            if (selectedChildren.length == 1)
            {
                var objs:Array = this.getObjects();
                var i:int = 0;
                while (i < objs.length) 
                {
                    if (!objs[i].selected && 
	                    	DrawingObject(objs[i]).hitTestPoint(DrawingObject(objs[i]).stage.mouseX, DrawingObject(objs[i]).stage.mouseY, true)
    	                	 && this.getChildIndex(objs[i]) > this.getChildIndex(selectedChildren[0]) )
    	            {
                        return true;
                    };
                    
                    i++;
                };
                return false;
            };
            
            return false;
        }

        public function selectShapeUnderMouse():void
        {
            var objs:Array = this.getObjects();
            var i:int = 0;
            
            this.removeListeners();
            resetSelectedChildren();
            objs = this.getObjects();
            i = objs.length-1;
            
            while (i >= 0) 
            {
                if (DrawingObject(objs[i]).hitTestPoint(DrawingObject(objs[i]).stage.mouseX, DrawingObject(objs[i]).stage.mouseY, true))
                {
                    dispatchEvent(new SelectEvent(SelectEvent.SELECT, true, true, DrawingObject(objs[i]), false));
                    break;
                };
                i--;
            };
        }

        public function get manipulator():Manipulator
        {
            return (_manipulator);
        }

        public function startMove(start:Point, switchModeIfUnmoved:Boolean):void
        {
            var i:int = 0;
            
            moveStartPoint = new Point(this.mouseX, this.mouseY);
            moveDMpMp = new Point(start.x - moveStartPoint.x, start.y - moveStartPoint.y);
            hasMoved = false;
            this.switchModeIfUnmoved = switchModeIfUnmoved;
			
            while (i < selectedChildren.length) 
            {
                DrawingObject(selectedChildren[i]).setMoveVars(this.moveStartPoint, manipulator.angle);
				i++;
            };
            
            this.addEventListener(MouseEvent.MOUSE_MOVE, this.changeMove);
            this.addEventListener(MouseEvent.MOUSE_UP, this.endMove);
		}

        public function get numSelectedChildren():Number
        {
            return (selectedChildren.length);
        }
		
        private function changeMove(evt:MouseEvent):void
        {
            var pt:Point;
            var obj:DrawingObject;

            if ( _manipulator == null ) return;
            
            pt = new Point(this.mouseX, this.mouseY);
            
            if ( numSelectedChildren == 1 && DrawingObject(selectedChildren[0]).constrained )
            {
                obj = selectedChildren[0];
                var xlen:Number = (Math.abs((Math.cos(_manipulator.angle) * _manipulator.width)) + Math.abs((Math.sin(_manipulator.angle) * _manipulator.height)));
                var ylen:Number = (Math.abs((Math.cos(_manipulator.angle) * _manipulator.height)) + Math.abs((Math.sin(_manipulator.angle) * _manipulator.width)));
                var minx:Number = (Math.min(-((_manipulator.height * Math.sin(_manipulator.angle))), 0) + Math.min((_manipulator.width * Math.cos(_manipulator.angle)), 0));
                var miny:Number = (Math.min((_manipulator.height * Math.cos(_manipulator.angle)), 0) + Math.min((_manipulator.width * Math.sin(_manipulator.angle)), 0));
                
                if ( !obj.withinXConstraints(pt.x + moveDMpMp.x + minx, -1) )
                {
                    pt.x = obj.nearestXConstraint(pt.x + moveDMpMp.x + minx) - moveDMpMp.x - minx;
                } 
                else if (!obj.withinXConstraints(pt.x + moveDMpMp.x + minx + xlen, 1))
                {
                    pt.x = obj.nearestXConstraint(pt.x + moveDMpMp.x + minx + xlen) - xlen - moveDMpMp.x - minx;
                };
                
                if ( !obj.withinYConstraints(pt.y + moveDMpMp.y + miny, -1) )
                {
                    pt.y = obj.nearestYConstraint(pt.y + moveDMpMp.y + miny) - moveDMpMp.y - miny;
                } 
                else if ( !obj.withinYConstraints(pt.y + moveDMpMp.y + miny + ylen, 1) )
                {
					pt.y = obj.nearestYConstraint(pt.y + moveDMpMp.y + miny + ylen) - ylen - moveDMpMp.y - miny;
                };
            };
            
            if (evt.ctrlKey)
            {
                var angle:Number = Math.atan2((pt.x - moveStartPoint.x), (pt.y - moveStartPoint.y));
                
                if ( angle >= Math.PI * (-45 / 180) && angle <= Math.PI * (45 / 180)
	                 || angle <= Math.PI * (-135 / 180)
    	             || angle >= Math.PI * (135 / 180) )
                {
                    _manipulator.moveTo(new Point(moveStartPoint.x, pt.y), moveDMpMp);
                } 
                else 
                {
                    _manipulator.moveTo(new Point(pt.x, moveStartPoint.y), moveDMpMp);
                };
                
            } 
            else 
            {
                _manipulator.moveTo(pt, moveDMpMp);
            };
            
            hasMoved = true;
			if(selected && selected.propertiesXML.prop.(@label=='action').@value!='add')
			{
				selected.propertiesXML.prop.(@label=='action').@value="update";
trace("drag 修改" + selected.propertiesXML.prop.(@label=='action').@value);
			}
        }

        private function endMove(evt:MouseEvent):void
        {
			if ( _manipulator == null ) return; // selection was removed by delete 
			
            if ( numSelectedChildren != 1 || !selectedChildren[0].constrained )
            {
                _manipulator.moveTo(new Point(this.mouseX, this.mouseY), moveDMpMp);
            };
			
            this.removeEventListener(MouseEvent.MOUSE_MOVE, this.changeMove);
            this.removeEventListener(MouseEvent.MOUSE_UP, this.endMove);
			
			refreshSubId();
//			
        }
        
        public function refreshSubId():void
        {
        	var j:int = 0;
        	
            var item:DrawingShape;
			            
            while (j < this.numChildren) 
            {
                if ( UIComponent(this.getChildAt(j)).className == 'DrawingShape' )
                {
                	item = DrawingShape(this.getChildAt(j));
                	
                	if ( item.isArea )
                	{
                		var i:int = 0;
                		var item2:DrawingShape;
			            while (i < this.numChildren) 
			            {
			                if ( UIComponent(this.getChildAt(i)).className == 'DrawingShape' )
			                {
			                	item2 = DrawingShape(this.getChildAt(i));
			                	if ( !item2.isArea )
			                	{
			                		if ( item.hitTestObject(item2) )
			                		{
			                			// subid
										var start:String = item.propertiesXML.prop.(@label=='subId').@value;
										if(start != item2.propertiesXML.prop.(@label=='subId').@value)
										{
											if(item2.propertiesXML.prop.(@label=='action').@value!='add')
												item2.propertiesXML.prop.(@label=='action').@value="update";
trace("subId=" + item2.propertiesXML.prop.(@label=='subId').@value +"\t pos=" + item2.propertiesXML.prop.(@label=='pos').@value);											
//											trace("改动区域影响的孩子action：" + item2.propertiesXML.prop.(@label=='action').@value);
//											var obj:Object = {};
//											obj.pageId = int(item2.propertiesXML.prop.(@label=='pageId')[0].@value);	
//											obj.subId = int(item2.propertiesXML.prop.(@label=='subId')[0].@value);	
//											obj.pos = int(item2.propertiesXML.prop.(@label=='pos')[0].@value);	
//											trace("drawingpage 删除  subId="  + obj.subId + "   pos=" + obj.pos);
////											m.cmsSite.delegate.delSitePages([obj]);
//											delArr.push(obj);
										}
										item2.propertiesXML.prop.(@label=='subId').@value = item.propertiesXML.prop.(@label=='subId').@value;
			                			item2.properties.itemUpdated(item2.propertiesXML.prop.(@label=='subId'),'@value');
										
			                		}
			                	}
                			}
                			++i;                			
               			}
               		}
                }
                j++;
            };
        	
        }
        
        public function startResize(start:Point, resize:Point, mouse:Point):void
        {
            if (!allLocked)
            {
                this.resizeStartPoint = start;
                this.resizeAngle = Math.atan2(resize.y - start.y, resize.x - start.x);
                this.resizeDMpRp = new Point(resize.x - mouse.x, resize.y - mouse.y);
                var i:int = 0;
                
                while (i < selectedChildren.length) {
                    selectedChildren[i].setResizeVars(start, resize, manipulator.angle);
                    i++;
                };
                
                Application.application.addEventListener(MouseEvent.MOUSE_MOVE, this.changeResize);
                Application.application.addEventListener(MouseEvent.MOUSE_UP, this.endResize);
                _tooltip = ToolTipManager.createToolTip(Math.round(_manipulator.width) + " x " + Math.round(_manipulator.height), 
                	Application.application.mouseX + 10, Application.application.mouseY + 10) as ToolTip;
            };
        }

        private function changeResize(evt:MouseEvent):void
        {        	
            var mouse:Point = new Point(this.mouseX, this.mouseY);
            
            if ( numSelectedChildren == 1 && DrawingObject(selectedChildren[0]).constrained)
            {
                var obj:DrawingObject = selectedChildren[0];
                
                if (!obj.withinXConstraints(mouse.x + this.resizeDMpRp.x))
                {
                    mouse.x = obj.nearestXConstraint(mouse.x + this.resizeDMpRp.x) - this.resizeDMpRp.x;
                };
                
                if (!obj.withinYConstraints(mouse.y + this.resizeDMpRp.y))
                {
                    mouse.y = obj.nearestYConstraint(mouse.y + this.resizeDMpRp.y) - this.resizeDMpRp.y;
                };
            };
            
            var pt:Point = new Point(mouse.x - this.resizeStartPoint.x, mouse.y - this.resizeStartPoint.y);

            if ( manipulator.angle % (2 * Math.PI) != 0 )
            {
                var ma:Matrix = new Matrix();
                ma.rotate(-_manipulator.angle);
                pt = ma.deltaTransformPoint(pt);
            };
            
            pt.x = pt.x + this.resizeDMpRp.x;
            pt.y = pt.y + this.resizeDMpRp.y;
            _manipulator.setSize(pt);
            _tooltip.text = Math.round(_manipulator.width) + " x " + Math.round(_manipulator.height);
            _tooltip.x = Application.application.mouseX + 10;
            _tooltip.y = Application.application.mouseY + 10;
        }
        
        private function endResize(evt:MouseEvent):void
        {
            ToolTipManager.destroyToolTip(_tooltip);
            Application.application.removeEventListener(MouseEvent.MOUSE_MOVE, this.changeResize);
            Application.application.removeEventListener(MouseEvent.MOUSE_UP, this.endResize);
            this.refreshSubId();
        }
        
        public function get canvasWidth():Number
        {
            return (_canvasWidth);
        }
        
        public function get canvasHeight():Number
        {
            return (_canvasHeight);
        }
        
		private function moveDepth(o:DisplayObject,depth:int=-1):void
		{
			if ( depth == -1 )	
				this.setChildIndex(o,this.numChildren-1);
			else
				this.setChildIndex(o,depth);
			
        }
        
        public function export():Array
        {
for(var n:int=0; n<delArr.length; n++)
{
trace("subId: " + delArr[n].subId +"  pos: " +delArr[n].pos +"   action:" + delArr[n].action + "\tsubId2: " + delArr[n].subId2 +"  pos2: " +delArr[n].pos2 );
}
trace("\n");
        	var j:int = 0;
        	
            var item:DrawingShape;
			
			var data:Array = new Array();
			
            while (j < this.numChildren) {

            	if ( UIComponent(this.getChildAt(j)).className == 'DrawingShape' )
            	{					
					
					
					var datum:Object = new Object;
		            var xml:XML;
	                item = DrawingShape(this.getChildAt(j));
	                xml = new XML("<item/>");
	                xml.@id = j;
	                xml.@x = item.x;
	                xml.@y = item.y;
	                xml.@width = item.width;
	                xml.@height =  item.height;
					xml.@label = String(item.propertiesXML.prop.(@label=='label')[0].@value); // label				
					
					datum.layout = xml.toXMLString();
					datum.id = String(item.propertiesXML.prop.(@label=='id')[0].@value); // label	
					datum.label = String(item.propertiesXML.prop.(@label=='label')[0].@value); // label	
					datum.time = String(item.propertiesXML.prop.(@label=='time')[0].@value); // label	
					datum.pageId = int(item.propertiesXML.prop.(@label=='pageId')[0].@value);	
					datum.subId = int(item.propertiesXML.prop.(@label=='subId')[0].@value);	
					datum.subId2 = int(item.propertiesXML.prop.(@label=='subId2')[0].@value);	
					datum.pos = int(item.propertiesXML.prop.(@label=='pos')[0].@value);	
					datum.pos2 = int(item.propertiesXML.prop.(@label=='pos2')[0].@value);	
					datum.productId = int(item.propertiesXML.prop.(@label=='productId')[0].@value);	
					datum.linkURL = String(item.propertiesXML.prop.(@label=='linkURL')[0].@value);	
					datum.linkTitle = String(item.propertiesXML.prop.(@label=='linkTitle')[0].@value);	
					datum.imageSrc = String(item.propertiesXML.prop.(@label=='imageSrc')[0].@value);	
					datum.imageAlt = String(item.propertiesXML.prop.(@label=='imageAlt')[0].@value);	
					datum.title = String(item.propertiesXML.prop.(@label=='title')[0].@value);	
					datum.detail = String(item.propertiesXML.prop.(@label=='detail')[0].@value);	
					datum.isArea = (String(item.propertiesXML.prop.(@label=='isArea')[0].@value)=='true')?1:0;	
					datum.productType = int(item.propertiesXML.prop.(@label=='productType')[0].@value);	

					datum.ad_title = String(item.propertiesXML.prop.(@label=='ad_title')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='ad_title')[0].@value);
					datum.ad_res = String(item.propertiesXML.prop.(@label=='ad_res')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='ad_res')[0].@value);	
					datum.ad_link = String(item.propertiesXML.prop.(@label=='ad_link')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='ad_link')[0].@value);	
					datum.ad_time_start = String(item.propertiesXML.prop.(@label=='timStart')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='timStart')[0].@value);	
					datum.ad_time_end = String(item.propertiesXML.prop.(@label=='timEnd')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='timEnd')[0].@value);	
					datum.ad_set_1 = String(item.propertiesXML.prop.(@label=='ad_set_1')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='ad_set_1')[0].@value);	
					datum.ad_set_2 = String(item.propertiesXML.prop.(@label=='ad_set_2')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='ad_set_2')[0].@value);	
					datum.next_ad_title = String(item.propertiesXML.prop.(@label=='nextTitle')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextTitle')[0].@value);	
					
//					datum.next_ad_res = String(item.propertiesXML.prop.(@label=='nextRes')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextRes')[0].@value);	
//					datum.next_ad_link = String(item.propertiesXML.prop.(@label=='nextLink')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextLink')[0].@value);	
//					datum.next_ad_time_start = String(item.propertiesXML.prop.(@label=='nextStart')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextStart')[0].@value);	
//					datum.next_ad_time_end = String(item.propertiesXML.prop.(@label=='nextEnd')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextEnd')[0].@value);	
//					datum.next_ad_set_1 = String(item.propertiesXML.prop.(@label=='nextSet_1')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextSet_1')[0].@value);	
//					datum.next_ad_set_2 = String(item.propertiesXML.prop.(@label=='nextSet_2')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='nextSet_2')[0].@value);		

					datum.action = String(item.propertiesXML.prop.(@label=='action')[0].@value)=='null'?'':String(item.propertiesXML.prop.(@label=='action')[0].@value);
trace("subId: " + datum.subId +"  pos: " +datum.pos +"   action:" + datum.action + "\t" +"subId2: " + datum.subId2 +"  pos2: " +datum.pos2);
					
					if(datum.action=="update" || datum.action=="del" || datum.action=='add')
					{
	                	data.push(datum);
					}
            	}
                j++;
            };
            
            return data;
        }
		
		// 初始化action属性
		public function initAction():void
		{
			unselect();
			selected = null;
			var j:int = 0;
			var item:DrawingShape;
			while (j < this.numChildren) {
				if ( UIComponent(this.getChildAt(j)).className == 'DrawingShape' )
				{					
					var xml:XML;
					item = DrawingShape(this.getChildAt(j));
					item.propertiesXML.prop.(@label=='action')[0].@value = "";
					item.propertiesXML.prop.(@label=='subId2')[0].@value = item.propertiesXML.prop.(@label=='subId')[0].@value;
					item.propertiesXML.prop.(@label=='pos2')[0].@value = item.propertiesXML.prop.(@label=='pos')[0].@value;
				}
				j++;
			};
		}
        
        public function toXML(page:XML):void
        {
        	var j:int = 0;
        	
            var drawingObject:DrawingObject;
            var instance:XML;
			            
            while (j < this.numChildren) {
            	
                drawingObject = DrawingObject(this.getChildAt(j));
                instance = new XML("<item/>");
                instance.@id = j;
                instance.@x = drawingObject.x;
                instance.@y = drawingObject.y;
                instance.@width = drawingObject.width;
                instance.@height =  drawingObject.height;
                instance.@angle = drawingObject.angle;
				instance.@label = drawingObject.className;				
                
                page.appendChild(instance);
                j++;
            };
        }
        
        public function parse(page:XML,pageIndex:int):void
        {       
        	var item:XML;
        	var drawingObject:DrawingObject;
        	
            for each (item in page.item)
            {
                drawingObject = new DrawingShape(item.@width, item.@height);
                drawingObject.x = item.@x;
                drawingObject.y = item.@y;
				drawingObject.loaded = true;
                this.addChild(drawingObject);
                drawingObject.activate();
                drawingObject.findExtents();
            };
            
        }

		/**
		 * 添加某一页所有元素 
		 * @param items  具体某页所有元素
		 * 
		 */		
        public function inport(items:Array):void // bye bye import
        {
			trace("添加的条目数：--------" + items.length);
			for each ( var item:Object in items )
			{
				this.addItem(item,Boolean(int(item.isArea)));
			}
        }
		

    }
}




